package com.mk.exnotice.event;

import com.mk.exnotice.markdown.SimpleMarkdownBuilder;
import com.mk.exnotice.pojos.Email;
import com.mk.exnotice.pojos.ExceptionNotice;
import com.mk.exnotice.properties.ExceptionNoticeProperties;
import com.mk.exnotice.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.ApplicationListener;
import java.lang.reflect.Field;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class ExceptionNoticeListener implements ApplicationListener<ExceptionNoticeEvent> {

    private MailService mailService;

    private MailProperties mailProperties;

    private ExceptionNoticeProperties properties;

    public ExceptionNoticeListener(MailService mailService,
                                   MailProperties mailProperties,
                                   ExceptionNoticeProperties properties){
        this.mailService = mailService;
        this.mailProperties = mailProperties;
        this.properties = properties;
    }

    @Override
    public void onApplicationEvent(ExceptionNoticeEvent event) {
        ExceptionNotice notice = event.getExceptionNotice();
        String title = String.format("来自项目%s的异常提醒", notice.getProject());
        try {
            Email email = Email.builder()
                    .subject(title)
                    .content(resolve(notice, title))
                    .from(mailProperties.getUsername())
                    .to(properties.getTo())
                    .template("notifyEmail.ftl")
                    .kvMap((HashMap<String, Object>) objectToMap(notice))
                    .build();
            // 发送模板邮件
            mailService.sendFreemarker(email);
        } catch (IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
    }


    public String resolve(ExceptionNotice exceptionNotice, String title) {
        return SimpleMarkdownBuilder.create().title(title, 1)
                .title("路径：", 2).text(exceptionNotice.getClassPath(), true)
                .title("方法名：" + SimpleMarkdownBuilder.bold(exceptionNotice.getMethod()), 2).title("参数信息：", 2)
                .orderPoint(exceptionNotice.getArgs()).title("异常信息：", 2).point(exceptionNotice.getMessage())
                .title("追踪信息：", 2).orderPoint(exceptionNotice.getTraceInfo())
                .title("最后一次出现时间：", 2)
                .text(exceptionNotice.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), true)
                .build();
    }


    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
